import { memo, isValidElement } from "react";
import { withRouter } from "next/router";
import Link from "next/link";
import Router from "next/router";
import Repo from "../components/Repo";

import { request, requestGithub } from "../lib/api";

import { Row, Col, List, Pagination, Button } from "antd";
import styled from "@emotion/styled";

const LANGUAGE = ["JavaScript", "HTML", "CSS", "TypeScript", "Java", "Rust"];
const SORT_TYPE = [
  {
    name: "Best Match",
  },
  {
    name: "Most Stars",
    value: "stars_count",
    order: "desc",
  },
  {
    name: "Most Forks",
    value: "forks_count",
    order: "desc",
  },
  {
    name: "Most Watches",
    value: "watches_count",
    order: "desc",
  },
  {
    name: "Last Push",
    value: "last_push_at",
    order: "desc",
  },
];

// 左侧选中样式
const selectedItemStyle = {
  borderLeft: "2px solid #e36209",
  fontWeight: 100,
};

// const Filter = ({ name, query, language, sort, order }) => {
//   // 将筛选条件push到router中
//   const doSearch = (config) => {
//     Router.push({
//       pathname: "/search",
//       query: { ...config },
//     });
//   };
//   return (
//     <a onClick={() => doSearch({ query, language, sort, order })}>{name}</a>
//   );
// };

const per_page = 20;

// 优化：Filter这个组件完全依赖props，只要props不变，就不用重新渲染
// 所以可以使用memo将其包裹，只要props不变就不会重新渲染
const FilterLangAndSort = memo(
  ({ name, query, language, sort, order, page }) => {
    let queryString = `?query=${query}`;
    if (language) queryString += `&language=${language}`;
    if (sort) queryString += `&sort=${sort}&order=${order || "desc"}`;
    queryString += `&page=${page || "1"}`;
    queryString += `&per_page=${per_page}`;
    return (
      // 鼠标放上去有链接
      // 有利于优化seo
      <Link href={`/search/${queryString}`}>
        {/* 针对 page 进行判断，page是一个a标签 */}
        {isValidElement(name) ? name : <a>{name}</a>}
      </Link>
    );
  }
);

function Search({ router, repos }) {
  const query = router.query;
  console.log(repos);

  return (
    <div className="root">
      <Row gutter={20}>
        <Col span={6}>
          <List
            bordered
            header={<span className="list-header">语言</span>}
            style={{ marginBottom: 20 }}
            dataSource={LANGUAGE}
            renderItem={(item) => {
              const selected = query.language === item;
              return (
                <List.Item style={selected ? selectedItemStyle : null}>
                  {selected ? (
                    <span>{item}</span>
                  ) : (
                    <FilterLangAndSort {...query} name={item} language={item} />
                  )}
                </List.Item>
              );
            }}
          />
          <List
            bordered
            header={<span className="list-header">排序</span>}
            dataSource={SORT_TYPE}
            renderItem={(item) => {
              let selected = false;
              if (item.name === "Best Match" && !query.sort) {
                selected = true;
              } else if (
                item.value === query.sort &&
                item.order === query.order
              ) {
                selected = true;
              }
              return (
                <List.Item style={selected ? selectedItemStyle : null}>
                  {selected ? (
                    <span>{item.name}</span>
                  ) : (
                    <FilterLangAndSort
                      {...query}
                      name={item.name}
                      sort={item.value || ""}
                      order={item.order || ""}
                    />
                  )}
                </List.Item>
              );
            }}
          />
        </Col>
        <Col span={18}>
          {repos.data.map((item) => (
            <Repo repo={item} key={item.id} />
          ))}
          <PageButton>
            <Button type="primary" ghost>
              {query.page > 1 ? (
                <FilterLangAndSort
                  {...query}
                  name={"上一页"}
                  page={Number(query.page) - 1}
                />
              ) : (
                "上一页"
              )}
            </Button>
            <Button type="primary" ghost>
              {query.page || 1}
            </Button>

            <Button type="primary" ghost>
              <FilterLangAndSort
                {...query}
                name={"下一页"}
                page={(Number(query.page) || 1) + 1}
              />
            </Button>
            {/* <Pagination
              pageSize={per_page}
              current={Number(query.page) || 1}
              onChange={handlePageChange}
              disabled={false}
              itemRender={(page, type, ol) => {
                const p =
                  type === "page"
                    ? page
                    : type === "prev"
                    ? page - 1
                    : page + 1;
                const name = type === "page" ? page : ol;
                return <FilterLangAndSort {...query} page={p} name={name} />;
              }}
            /> */}
          </PageButton>
        </Col>
      </Row>
      <style jsx>
        {`
          .root {
            padding: 20px 0;
          }
          .list-header {
            font-weight: 800;
            font-size: 16px;
          }
        `}
      </style>
    </div>
  );
}

Search.getInitialProps = async ({ ctx }) => {
  const { query, sort, language, order, page } = ctx.query;

  if (!query) {
    return {
      repos: {
        total_count: 0,
      },
    };
  }

  let queryString = `?q=${query}`;
  if (language) queryString += `&language=${language}`;
  if (sort) queryString += `&sort=${sort}&order=${order || "desc"}`;
  queryString += `&page=${page || 1}`;
  queryString += `&per_page${per_page}`;

  const repos = await request(
    {
      url: `/search/repositories${queryString}`,
    },
    ctx.req,
    ctx.res
  );
  return {
    repos,
  };
};

const PageButton = styled.div`
  display: flex;
  justify-content: center;
  margin: 10px 0;
`;

export default withRouter(Search);
